package hotel.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.map.ObjectMapper;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import hotel.entity.Authority;
import hotel.entity.Reserve;
import hotel.entity.Role;
import hotel.entity.Room;
import hotel.entity.Sales;
import hotel.entity.SalesLineItem;
import hotel.entity.User;
import hotel.service.IAuthorityService;
import hotel.service.IReserveService;
import hotel.service.IRoleService;
import hotel.service.IRoomService;
import hotel.service.ISalesLineItemService;
import hotel.service.ISalesService;
import hotel.service.IUserService;
import util.JSONUtil;
import util.StringUtil;

@Controller
public class UserController {
	// Jackson
	private final static ObjectMapper mapper = new ObjectMapper();
	private static Logger log = Logger.getLogger(UserController.class);

	@Autowired
	private IUserService<User> userService;
	@Autowired
	private IRoleService<Role> roleService;
	@Autowired
	private IAuthorityService<Authority> authorityService;
	@Autowired
	IReserveService<Reserve> reserveService;
	@Autowired
	ISalesService<Sales> salesService;
	@Autowired
	ISalesLineItemService<SalesLineItem> itemService;
	@Autowired
	IRoomService<Room> roomService;

	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login() {
		return "user/login";
	}

	/**
	 * 用户登录 用户的账号、密码正确时，跳转到首页，并将用户拥有的权限放到Session中，便于拦截器进行用户权限的校验 账号或密码错误时，回到登录页面
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String loginUser(Model model,User u, HttpServletRequest request) {
		User user = userService.validate(u.getAccount(), u.getPassword());
		if (user != null) {
			model.addAttribute("reserve_count", reserveService.getReserveCount());
			model.addAttribute("sales_count", salesService.getTotalSale());
			model.addAttribute("person_count", itemService.getCheckinCustomerCount());
			model.addAttribute("room_count", roomService.getAvailableCount());
			model.addAttribute("user_count", userService.getTotalCount("User"));
			//首页数据
			Map<String,Double> map=salesService.getSaleStatistic();
			model.addAttribute("categories", StringUtil.getSalesCategories(map));
			model.addAttribute("data", StringUtil.getSalesDate(map));
			model.addAttribute("roomStatistic", JSONUtil.roomStatisticsToJson(roomService.getRoomStatistics()));
			// admin账号拥有所有权限
			if (user.getAccount().equals("admin")) {
				request.getSession().setAttribute("noAuthority", "");
				request.getSession().setAttribute("loginUser", user);
				return "index";
			} else {// 普通用户
				Role role = roleService.findById(Role.class, user.getRole().getRoleid());
				// 没有的权限
				StringBuffer buffer = new StringBuffer();// SttringBuffer用于存放没有的权限，隐藏导航栏
				List<Authority> list = authorityService.findNoAuthority(user.getRole().getRoleid());
				for (Authority a : list) {
					// 将没有的权限组装成字符串,在menu.jsp页面使用JQeury隐藏菜单
					buffer.append(a.getPath() + ",");
				}
				request.getSession().setAttribute("noAuthority", buffer.toString());
				// 拥有的权限
				// map存放拥有的权限,放在session中,在拦截器中使用
				HashMap<String, String> authsMap = new HashMap<>();
				for (Authority a : role.getAuthoritys()) {
					// Key为路径,Value为中文名称
					authsMap.put(a.getPath(), a.getAuthorityName());
				}
				request.getSession().setAttribute("loginUser", user);
				request.getSession().setAttribute("loginUser_authority", authsMap);
				log.info(user.getName() + "登录系统");
				return "index";
			}
		} else {// user为空,账号或者密码错误
			request.setAttribute("message", "用户名或密码错误");
		}
		return "user/login";
	}

	@RequestMapping(value = "logout")
	public String logout(HttpServletRequest request) {
		request.getSession().removeAttribute("loginUser");
		request.getSession().removeAttribute("loginUser_authority");
		return "user/login";
	}

	@RequestMapping(value = "userManagement")
	public String userManagement() {
		return "user/userlist";
	}

	@ResponseBody
	@RequestMapping(value = "userlist")
	public String getUserList(Model model) {
		String json = null;
		try {
			json = mapper.writeValueAsString(userService.listAll("User"));
			json = "{\"data\":" + json + "}";
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json;
	}

	@RequestMapping(value = "addUser", method = RequestMethod.GET)
	public String add(Model model) {
		model.addAttribute("roleList", roleService.listAll("Role"));
		return "user/add";
	}

	@ResponseBody
	@RequestMapping(value = "addUser", method = RequestMethod.POST)
	public String addUser(User user, @RequestParam("user_image") MultipartFile file, 
			HttpServletRequest request) {
		try {
			String path = request.getServletContext().getRealPath("/images/users");// 上传文件路径
			if (!file.isEmpty()) {
				// 上传文件名
				String filename = file.getOriginalFilename();
				File filepath = new File(path, filename);
				// 判断路径是否存在，如果不存在就创建一个
				if (!filepath.getParentFile().exists()) {
					filepath.getParentFile().mkdirs();
				}
				// 将上传文件保存到一个目标文件当中
				file.transferTo(new File(path + File.separator + filename));
				user.setImage("images/users/"+file.getOriginalFilename());
			}
			if (userService.save(user))
				return JSONUtil.returnSuccess();
			else
				return JSONUtil.returnFailure();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return JSONUtil.returnFailure();
	}

	@RequestMapping(value = "editUser", method = RequestMethod.GET)
	public String edit(int userid, Model model) {
		model.addAttribute("user", userService.findById(User.class, userid));
		model.addAttribute("roleList", roleService.listAll("Role"));
		return "user/edit";
	}

	@ResponseBody
	@RequestMapping(value = "editUser", method = RequestMethod.POST)
	public String editUser(User user,@RequestParam("user_image") MultipartFile file, 
			HttpServletRequest request) {
		try {
			String path = request.getServletContext().getRealPath("/images/users");// 上传文件路径
			if (!file.isEmpty()) {
				// 上传文件名
				String filename = file.getOriginalFilename();
				File filepath = new File(path, filename);
				// 判断路径是否存在，如果不存在就创建一个
				if (!filepath.getParentFile().exists()) {
					filepath.getParentFile().mkdirs();
				}
				// 将上传文件保存到一个目标文件当中
				file.transferTo(new File(path + File.separator + filename));
				user.setImage("images/users/"+file.getOriginalFilename());
			}
			if (userService.update(user))
				return JSONUtil.returnSuccess();
			else
				return JSONUtil.returnFailure();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return JSONUtil.returnFailure();
	}

	@ResponseBody
	@RequestMapping(value = "deleteUser")
	public String deleteUser(int userid) {
		if (userService.deleteById("User", userid))
			return JSONUtil.returnSuccess();
		else
			return JSONUtil.returnFailure();
	}

	@RequestMapping(value = "validateUser")
	public void validate() {

	}
}
